package com.bdzl.ecs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdzl.ecs.dao.ContractTmplDao;
import com.bdzl.ecs.service.ContractOnlineService;
import com.bdzl.ecs.service.ContractOnlineSignrecService;
import com.bdzl.ecs.service.ContractTmplService;
import com.bdzl.ecs.servicefeign.EnterpriseFeignService;
import com.bdzl.ecs.servicefeign.FddCaEntFeignService;
import com.bdzl.ecs.servicefeign.FddCaPersonalFeignService;
import com.bdzl.ecs.util.contractUtils.ContractUtils;
import com.bdzl.pub.config.Constant;
import com.bdzl.pub.entity.data.FddCaPersonalDO;
import com.bdzl.pub.entity.loan.ContractOnlineDO;
import com.bdzl.pub.entity.loan.ContractOnlineSignrecDO;
import com.bdzl.pub.entity.loan.ContractTmplDO;
import com.bdzl.pub.util.ip.ipUtils;
import com.bdzl.pub.util.param.R;
import com.bdzl.pub.vo.loan.ContractTmplVO;
import com.bdzl.pub.vo.util.SigningAContractVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
@Transactional(rollbackFor = Exception.class)
public class ContractTmplServiceImpl implements ContractTmplService {
    @Autowired
    private ContractTmplDao contractTmplDao;
    @Autowired
    private FddCaPersonalFeignService fddCaPersonalFeignService;
    @Autowired
    private FddCaEntFeignService fddCaEntFeignService;
    @Autowired
    private EnterpriseFeignService enterpriseFeignService;
    @Autowired
    private ContractTmplService contractTmplService;
    @Autowired
    private ContractOnlineService contractOnlineService;
    @Autowired
    private ContractOnlineSignrecService contractOnlineSignrecService;

    @Override
    public ContractTmplDO get(Integer tmplId) {
        return contractTmplDao.get(tmplId);
    }

    @Override
    public List<ContractTmplDO> list(Map<String, Object> map) {
        return contractTmplDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return contractTmplDao.count(map);
    }

    @Override
    public int save(ContractTmplDO contractTmpl) {
        return contractTmplDao.save(contractTmpl);
    }

    @Override
    public int update(ContractTmplDO contractTmpl) {
        return contractTmplDao.update(contractTmpl);
    }

    @Override
    public int remove(Integer tmplId) {
        return contractTmplDao.remove(tmplId);
    }

    @Override
    public int batchRemove(Integer[] tmplIds) {
        return contractTmplDao.batchRemove(tmplIds);
    }

    @Override
    public List<ContractTmplVO> listAndUser(Map map) {
        return contractTmplDao.listAndUser(map);
    }

    @Override
    public int listAndUserCount(Map map) {
        return contractTmplDao.listAndUserCount(map);
    }


    /**
     * 对接报件流程，客户申请CA证书，自动生成合同，企业自动盖章，最终生成url发送给客户，客户签章通过，回调平台接口。
     * @param signingAContractVO
     * @param userId  当前登录者id
     * @return JSON
     */
    @Override
    public String signingAContract(SigningAContractVO signingAContractVO, Integer userId) {
        if ("0".equals(signingAContractVO.getSignMethod())) { //对私
            JSONObject jsonObject = null;
            if ("0".equals(signingAContractVO.getSignType())) {//没有申请Ca证书
                //1.申请CA证书
                String response = ContractUtils.CACustomer(signingAContractVO.getUserInfoDO().getConName(), signingAContractVO.getUserInfoDO().getConEmail(), signingAContractVO.getUserInfoDO().getConCardid(), "0", signingAContractVO.getUserInfoDO().getConMobile());
                jsonObject = JSON.parseObject(response);
                if ("1000".equals(jsonObject.get("code"))) {
                    //认证通过，data_fdd_ca_personal 表中添加数据
                    FddCaPersonalDO fddCaPersonal = new FddCaPersonalDO();
                    fddCaPersonal.setCapCardId(signingAContractVO.getUserInfoDO().getConCardid());
                    fddCaPersonal.setCapCustomerId(jsonObject.get("customer_id").toString());
                    R r = fddCaPersonalFeignService.save(fddCaPersonal);
                } else {
                    return response;
                }
            } else { //有CA证书
                //1.申请CA证书
                String response = ContractUtils.CACustomer(signingAContractVO.getUserInfoDO().getConName(), signingAContractVO.getUserInfoDO().getConEmail(), signingAContractVO.getUserInfoDO().getConCardid(), "0", signingAContractVO.getUserInfoDO().getConMobile());
                jsonObject = JSON.parseObject(response);
            }
            //2.创建合同
            //2.1获取合同模板信息
            ContractTmplDO contractTmplDO = contractTmplService.get(signingAContractVO.getContractId());
            //合同编号 只允许长度<=32的英文或数字字符
            String contract_id = System.currentTimeMillis() + "";
            String response1 = ContractUtils.invokeGenerateContract(contractTmplDO.getTmplName(), contractTmplDO.getTmplNo() + "", null, "0", signingAContractVO.getParamter(), null, contract_id);
            JSONObject json = JSONObject.parseObject(response1);
            json.put("contract_id", contract_id);
            if ("操作成功".equals(json.get("msg"))) {
                ContractOnlineDO contractOnline = new ContractOnlineDO();
                contractOnline.setOnlineConNo(Long.parseLong(contract_id));
                contractOnline.setOnlineConTitle(contractTmplDO.getTmplName());
                contractOnline.setOnlineTmplId(Long.parseLong(contractTmplDO.getTmplNo() + ""));
                contractOnline.setOnlineFddGetUrl(json.get("viewpdf_url").toString());
                contractOnline.setOnlineFddOnloadUrl(json.get("download_url").toString());
                contractOnline.setOnlineCreuser(userId);
                int a = contractOnlineService.save(contractOnline);
            } else {
                return response1;
            }
            //3.企业盖章(自动盖章)
            String transactionId = ipUtils.random(5);
            String response2 = ContractUtils.invokeExtSignAuto(transactionId + signingAContractVO.getContractType() + signingAContractVO.getOrderNo(), Constant.FDD_CODE, "1", contract_id, contractTmplDO.getTmplName(), signingAContractVO.getSignKeyword(), null, Constant.return_url);
            saveContractOnlineSignrec(contract_id, Constant.platformName, "Seal", null, userId, signingAContractVO.getOrderNo(),1,Long.parseLong(transactionId));
            //4.客户签章(手动签章)
            if ("QRcode".equals(Constant.solution)) {//二维码
                String transactionId2 = ipUtils.random(5);
                String response3 = ContractUtils.invokeExtSign(transactionId2 + signingAContractVO.getContractType() + signingAContractVO.getOrderNo(), jsonObject.get("customer_id").toString(), contract_id, contractTmplDO.getTmplName(), signingAContractVO.getSignKeyword(), null, Constant.return_url, null);
                saveContractOnlineSignrec(contract_id, signingAContractVO.getUserInfoDO().getConCardid(), "Autograph", null, userId, signingAContractVO.getOrderNo(),0,Long.parseLong(transactionId2));
                return response3;
            } else if ("SMS".equals(Constant.solution)) {//短信
                //4.客户签章(手动签章) todo-----客户签章进入生产环境
                String transactionId2 = ipUtils.random(5);
                String respose3 = ContractUtils.pushdocExtsign(transactionId2 + signingAContractVO.getContractType(), "1622114735921", "6B5E034F7B7E9FA0CF9B0C1C89E105DD", "赵春宇测试文档", "被告知人");
                saveContractOnlineSignrec(contract_id, signingAContractVO.getUserInfoDO().getConCardid(), "Autograph", null, userId, signingAContractVO.getOrderNo(),0,Long.parseLong(transactionId2));
                return respose3;
            }
        } else {//对公
        }
        return "不知名错误";
    }


    /**
     * 将合同签署记录保存到表中
     *
     * @param cos_con_id    合同ID，外键
     * @param cos_signer    签署人
     * @param cos_sign_way  签署方式
     * @param cos_sign_info 签署的内容
     * @param userId        创建人
     * @param cos_odr       订单号
     * @Param cos_state     签署状态 0:代签署 1：已签署
     * @param cos_transaction 交易号
     */
    private void saveContractOnlineSignrec(String cos_con_id, String cos_signer, String cos_sign_way, String cos_sign_info, Integer userId, String cos_odr,int cos_state,Long cos_transaction) {
        ContractOnlineSignrecDO contractOnlineSignrec = new ContractOnlineSignrecDO();
        contractOnlineSignrec.setCosConId(Long.parseLong(cos_con_id));
        contractOnlineSignrec.setCosSigner(cos_signer);
        contractOnlineSignrec.setCosSignWay(cos_sign_way);
        contractOnlineSignrec.setCosSignInfo(cos_sign_info);
        contractOnlineSignrec.setCosCreuser(userId);
        contractOnlineSignrec.setCosSignTime(new Date());
        contractOnlineSignrec.setCosOdr(cos_odr);
        contractOnlineSignrec.setCosTransaction(cos_transaction);
        contractOnlineSignrec.setCosState(cos_state);
        contractOnlineSignrecService.save(contractOnlineSignrec);
    }

    /**
     * 合同推送
     *
     * @param transaction_id 交易号
     * @param contract_id    合同编号
     * @param customer_id    客户编号
     * @param doc_title      文档标题
     * @param sing_keyword   定位关键字
     * @return
     */
    @Override
    public String pushdocExtsign(String transaction_id, String contract_id, String customer_id, String doc_title, String sing_keyword) {
        return ContractUtils.pushdocExtsign(transaction_id, contract_id, customer_id, doc_title, sing_keyword);
    }

}
